import { defineStore } from 'pinia'
import { routeMapper } from '@/router/route-mapper'
import router, { errorRoutes, constantRoutes, resetRouter } from '@/router'
import type { RouteType } from 'vue-router'
import { useTagsViewStore } from './tagsView'

function generateRoutes(routes: RouteType[] = []) {
  const res: any[] = []
  routes.forEach((route) => {
    // 找到本地对照route
    const routeMap = routeMapper[route.path]
    if (routeMap) {
      // 处理meta
      if (routeMap.meta) {
        routeMap.meta.title = route.name
      }
      routeMap.name = route.name
      // 处理path
      if (route.path.split('/').length === 2) {
        // 根菜单
        routeMap.path = route.path
      } else {
        const pathArr = route.path.split('/')
        routeMap.path = pathArr[pathArr.length - 1]
      }
      if (route.children) {
        routeMap.children = generateRoutes(route.children)
      }
      res.push(routeMap)
    }
  })
  return res
}

// setup
export const usePermissionStore = defineStore('permission', () => {
  // 路由
  const asyncRoutes = ref<any>([])

  // 生成路由
  const generateAsyncRoutes = async () => {
    // 重置所有路由
    resetRouter()
    // 获取动态路由
    const apiRoutes: RouteType[] = [
      {
        name: 'api大全22',
        path: '/api-dashboard',
        children: [
          {
            name: 'api大全333',
            path: '/api-dashboard/index',
            children: null
          }
        ]
      }
    ]
    // 处理动态路由
    const accessRoutes = generateRoutes(apiRoutes)
    // 添加动态路由
    accessRoutes.concat(errorRoutes).forEach((route) => {
      router.addRoute(route)
    })

    // if (accessRoutes && accessRoutes.length) {
    //   let firstRoutePath = accessRoutes[0].path
    //   if (accessRoutes[0].children && accessRoutes[0].children.length) {
    //     firstRoutePath = `${firstRoutePath}/${accessRoutes[0].children[0].path}`
    //   }
    //   // 重置 / 访问
    //   router.addRoute({
    //     path: '/',
    //     name: 'Root',
    //     redirect: firstRoutePath
    //   })
    // }

    // 拼接完整路由
    asyncRoutes.value = constantRoutes.concat(accessRoutes).concat(errorRoutes)
    // 重置tagsView
    const tagsViewStore = useTagsViewStore()
    tagsViewStore.delAllViews()
  }
  // 重置动态路由
  const resetAsyncRouter = () => {
    asyncRoutes.value = []
  }

  return { asyncRoutes, resetAsyncRouter, generateAsyncRoutes }
})
